package mgoconf

import (
	"encoding/json"
	"gopkg.in/mgo.v2"
	"io/ioutil"
)

type Config struct {
	// Info for dialing
	Conn *mgo.DialInfo

	// Safety Characteristics
	Safety *mgo.Safe
}

func New() *Config {
	return &Config{
		Conn: &mgo.DialInfo{
			Database: "giraffe",
			Addrs:    []string{"localhost"},
			Direct:   true,
		},
		Safety: &mgo.Safe{},
	}
}

func Read(fn string) (*Config, error) {
	cfg := New()

	file, err := ioutil.ReadFile(fn)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(file, cfg)
	if err != nil {
		return nil, err
	}

	return cfg, nil
}

func (cfg *Config) Connect() (*mgo.Session, error) {
	sess, err := mgo.DialWithInfo(cfg.Conn)
	if err != nil {
		return nil, err
	}

	// Set Safety Parameters
	sess.SetSafe(cfg.Safety)
	return sess, nil
}
